//
//  SearchViewController.m
//  ZhuiKe55like
//
//  Created by junseek on 14-12-17.
//  Copyright (c) 2014年 五五来客 李江. All rights reserved.
//

#import "SearchViewController.h"
#import "RHTableView.h"
#import "UserColleagueTableViewCell.h"
#import "SelectWebUrlViewController.h"

@interface SearchViewController ()<UISearchBarDelegate,RHTableViewDelegate>{//UserTableViewCellDelegate
    
    NSMutableArray *searchDataArray;
    NSMutableArray *oldDataArrayTemp;
    RHTableView *table_user;
    UISearchBar *mySearchBar;
    
}


@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initComponents];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   
    
    [self.navigationItem setHidesBackButton:YES];
    KKNavigationController *kNav=(KKNavigationController *)self.navigationController;
    kNav.canDragBack=NO;
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [table_user setEditing:NO];
    KKNavigationController *kNav=(KKNavigationController *)self.navigationController;
    kNav.canDragBack=YES;
    [table_user cancelDownload];
}

- (void)initComponents{
    UIView *viewTemp=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth-10, 44)];
    viewTemp.clipsToBounds=YES;
//    viewTemp.backgroundColor=[UIColor whiteColor];
    
    
    oldDataArrayTemp=[[NSMutableArray alloc] initWithArray:[self.otherInfo objectForJSONKey:@"list"]];
    searchDataArray=[[NSMutableArray alloc] initWithCapacity:0];
    
    mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,0, W(viewTemp)-50, 44)];
    mySearchBar.delegate = self;
    mySearchBar.placeholder=@"搜索";
    [mySearchBar becomeFirstResponder];
    [viewTemp addSubview:mySearchBar];
    
    UIButton *backBtn=[RHMethods buttonWithFrame:CGRectMake(XW(mySearchBar),0, 50, 44) title:@"取消" image:@"" bgimage:@""];//
    [backBtn addTarget:self action:@selector(SearchBackButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [viewTemp addSubview:backBtn];
    
    
    [mySearchBar setTintColor:rgbBlue];

  
    [self navbarTitle:@"   "];
    for (UIView *viewT in [self.navView subviews]) {
        [viewT removeFromSuperview];
    }
    [self.navView addSubview:[RHMethods imageviewWithFrame:self.navView.bounds defaultimage:@"headbg"]];
    [viewTemp setFrame:CGRectMake(0, 20, kScreenWidth, 44)];
    [mySearchBar setFrame:CGRectMake(0,0, W(viewTemp)-45, 44)];
    backBtn.frameX=XW(mySearchBar)-5;
    [self.navView addSubview:viewTemp];
    
    [mySearchBar setBackgroundImage:[[Utility Share] imageFromColor:[UIColor clearColor] rect:mySearchBar.frame.size]];
    UITextField *searchField=[mySearchBar valueForKey:@"_searchField"];
    searchField.backgroundColor = [UIColor whiteColor];

    
    
    table_user=[[RHTableView alloc]initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, kContentHeight)];
    [table_user showRefresh:NO LoadMore:NO];
    table_user.delegate = self;
    table_user.dataSource = self;
//    table_user.delegate2=self;
    [table_user setBackgroundColor:rgbGray];
    [table_user setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [table_user registerClass:[UserColleagueTableViewCell class] forCellReuseIdentifier:@"UserColleagueTableViewCell"];
    [table_user setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    
    [self.view addSubview:table_user];

    
}
#pragma mark button

#pragma mark pop


#pragma mark UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{//
    table_user.isSoapDomain=NO;
    table_user.progressHUDMask = SVProgressHUDMaskTypeNil;
    [table_user showRefresh:NO LoadMore:YES];

    if([self.userInfo isEqualToString:@"colleague_search"]){
        [table_user showRefresh:NO LoadMore:NO];
        [self loadSearchViewData_Users_search:searchText];
       
    }
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    //  [self loadViewSearchAddress:searchBar.text];
    [table_user setContentOffset:CGPointZero animated:YES];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    [self searchBar:searchBar textDidChange:searchBar.text];

}
-(void)SearchBackButtonClicked{
    [mySearchBar resignFirstResponder];

    CATransition *transition = [CATransition animation];
    transition.duration =0.4;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
   
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    
    [self.navigationController popViewControllerAnimated:NO];
   
    
}

#pragma mark search
-(void)loadSearchViewData_Users_search:(NSString *)strTxt{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSMutableArray *tempResults = [NSMutableArray array];
        
        NSArray *tArray=oldDataArrayTemp;
        if ([strTxt notEmptyOrNull]) {
            NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
            
            for (int i = 0; i < tArray.count; i++) {
                NSDictionary *dict=tArray[i];
                if (!dict) {
                    continue;
                }
               
                
                NSString *storeString = [dict valueForJSONStrKey:@"name"];
                NSRange storeRange = NSMakeRange(0, storeString.length);
                NSRange foundRange = [storeString rangeOfString:strTxt options:searchOptions range:storeRange];
                if (foundRange.length) {
                    [tempResults addObject:dict];
                }else{
                    NSString *storeStringT = [dict valueForJSONStrKey:@"position"];
                    NSRange storeRangeT = NSMakeRange(0, storeStringT.length);
                    NSRange foundRangeT = [storeStringT rangeOfString:strTxt options:searchOptions range:storeRangeT];
                    if (foundRangeT.length) {
                        [tempResults addObject:dict];
                    }else{
//                        NSString *storeStringT = [dict valueForJSONStrKey:[self.userInfo isEqualToString:@"colleague_search"]?@"jname":@"job"];
//                        NSRange storeRangeT = NSMakeRange(0, storeStringT.length);
//                        NSRange foundRangeT = [storeStringT rangeOfString:strTxt options:searchOptions range:storeRangeT];
//                        if (foundRangeT.length) {
//                            [tempResults addObject:dict];
//                        }else{
//                            NSString *storeStringT = [dict valueForJSONStrKey:@"addr"];
//                            NSRange storeRangeT = NSMakeRange(0, storeStringT.length);
//                            NSRange foundRangeT = [storeStringT rangeOfString:strTxt options:searchOptions range:storeRangeT];
//                            if (foundRangeT.length) {
//                                [tempResults addObject:dict];
//                            }else{
//                                NSString *storeStringT = [dict valueForJSONStrKey:@"first"];
//                                NSRange storeRangeT = NSMakeRange(0, storeStringT.length);
//                                NSRange foundRangeT = [storeStringT rangeOfString:strTxt options:searchOptions range:storeRangeT];
//                                if (foundRangeT.length) {
//                                    [tempResults addObject:dict];
//                                }
//                            }
//                        }
                    }
                }
            }
        }else{
            
            [tempResults addObjectsFromArray:tArray];
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [searchDataArray removeAllObjects];
            [searchDataArray addObjectsFromArray:tempResults];
            [table_user reloadData];
        });
    });
    
       
}

#pragma mark tableView
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic=[searchDataArray objectAtIndex:indexPath.row];
    if ([dic objectForJSONKey:@"list"]) {
        return 44;
    }
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return searchDataArray.count;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic=[searchDataArray objectAtIndex:indexPath.row];
        UserColleagueTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserColleagueTableViewCell" forIndexPath:indexPath];
        [cell setValueForDictionary:dic indexPath:indexPath type:@"search"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [mySearchBar resignFirstResponder];
    NSDictionary *dic=[searchDataArray objectAtIndex:indexPath.row];
    NSMutableDictionary *dicCard=[[NSMutableDictionary alloc] initWithDictionary:dic];
    [dicCard setValue:[dic valueForJSONStrKey:@"card"] forKey:@"url"];
    [dicCard setValue:[dic valueForJSONStrKey:@"ids"] forKey:@"uid"];
    [dicCard setValue:NSStringFromClass([self class]) forKey:@"controller"];
    [self pushController:[SelectWebUrlViewController class] withInfo:@"shareCard" withTitle:@" " withOther:dicCard];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [mySearchBar resignFirstResponder];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
